package thread.pool;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-08-06 14:06
 **/
public class CustomThreadFactory implements ThreadFactory {

    private final String pollName;
    private final int priority;
    private final boolean isDaemon;
    private AtomicInteger threadNumber = new AtomicInteger(1);

    public CustomThreadFactory(String pollName, int priority, boolean isDaemon) {
        this.pollName = pollName;
        if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) {
            throw new IllegalArgumentException("优先级变量应该在1~10之间！");
        }
        this.priority = priority;
        this.isDaemon = isDaemon;
    }

    @Override
    public Thread newThread(final Runnable r) {
        // 创建线程
        Thread thread  = new Thread(r, pollName + "-thread-" + threadNumber.getAndIncrement());

        // 设置线程属性（优先级 + 是否守护进程）
        thread.setPriority(this.priority);
        thread.setDaemon(isDaemon);

        // 可选：设置未捕获异常
        thread.setUncaughtExceptionHandler((t, e) -> {
            System.out.println("线程" + t.getName() + "发生未捕获异常：" + e.getMessage());
        });

        return thread;
    }

    public static void main(String[] args) {
        // 创建线程工厂
        CustomThreadFactory threadFactory = new CustomThreadFactory("task-pool", 5, false);

        // 创建线程
        Thread thread = threadFactory.newThread(() -> {
            System.out.println("当前线程：" + Thread.currentThread().getName());
            System.out.println("优先级：" + Thread.currentThread().getPriority());
            System.out.println("是否守护线程：" + Thread.currentThread().isDaemon());
        });

        // 启动线程
        thread.start();
    }
}
